<?php
/**
@自动生成 BY Kupe框架 www.kupebank.com
#date : 2018-03-04 09:18:29
#path : app/model/mode.class.php
mode 表
*/
class modeModel extends db
{
	/**
	参数: 模型TAG,返回此TAG的记录
	*/
	function check($tag)
	{
		$rt = $this->where("`tag`='{$tag}'")->find();
		
		return $rt;
	}
	/**
	删除模型,逻辑处理
	参数 $rs 是模型的记录,如果是id的话,为模型的ID
	**/
	function dodel($rs)
	{		
		if(is_numeric($rs))
		{
			$rs = $this->pk($rs)->find();
		}
		//删除模型下的字段
		$this->where("mid='{$rs['id']}'")
			->table("mode_field")
			->delete();

		$table = getconfig("db_prefix") . "my_{$rs['tag']}";
		$sql = "DROP TABLE IF  EXISTS `{$table}` ";

		//删除此模型下的分类
		$db = m('category');
		$categorys = $db->where("mid='{$rs['id']}'")->findAll();
		foreach($categorys as $k => $v)
		{
			$db->dodelcategory($v['id']);
		}

		

		//删除此模型 => 分类 => 对应的文章


		$this->query($sql);
		return $this->pk($rs['id'])->delete();		
	}	
	/**
	删除字段,逻辑处理
	$rs = 字段记录,  或 字段表的ID
	**/
	function dodelfield($rs)
	{		
		if(is_numeric($rs))
		{
			$rs = $this->table("mode_field")->pk($rs)->$find();
		}
		$table = getconfig("db_prefix") . "my_{$rs['tag']}";


		$sql = "ALTER TABLE `{$table}` DROP `{$rs['field']}`";
		$this->query($sql);

		return $this->table("mode_field")->pk($rs['id'])->delete();		
	}

	/**
	参数: 模型field ,返回此TAG的记录
	mid 模型ID,
	*/
	function checkField($field, $mid)
	{
		$rt = $this->table("mode_field")
			->where("`field`='{$field}' AND mid='{$mid}'")->find();
		
		return $rt;
	}
	/**
	参数: 模型ID , 计算并返回 内容表中新的 字段名
	计算方法: 获取已经使用的内容表KEY,
	*/
	function getNewMap($mid)
	{
		$rs = $this->table("mode_field")
			->where("mid='{$mid}'")->findAll();
		$rec = array();
		foreach($rs as $k => $v)
		{
			$rec[$v['map']] = $v['map'];
		}
		$map = 0;
		for($i = 0; $i <= 30; $i++)
		{
			if(!isset($rec[$i]))
			{
				$map = $i;
				break;
			}
		}
		return $map;
	}

	/*
	参数 $rs 是模型的记录,如果是id的话,为模型的ID
	*/
	function addMode($rs)
	{
		if(is_numeric($rs))
		{
			$rs = $this->pk($rs)->find();
		}
		$rec[] = array(
			'field' => 'title',
			'name' => '标题',
			'request' => 1,
			'form' => '{input}',
		);

		$rec[] = array(
			'field' => 'name2',
			'name' => '自定义网址',
			'form' => '{input}',
		);    
		    

		$rec[] = array(
			'field' => 'keyword',
			'name' => '文章关键字',
			'form' => '{input}',
		);
        

		$rec[] = array(
			'field' => 'desc',
			'name' => '文章描述',
			'form' => '{textarea}',
		);
		$rec[] = array(
			'field' => 'content',
			'name' => '文章内容',
			'form' => '{editor}',
		);  
		
		foreach($rec as $k => $v)
		{
			$v['mid'] = $rs['id'];
			//$v['map'] = $v['field'];
			$v['porder'] = $k+1;
			//$rec[$k] = $v;
			$this->values($v)->table('mode_field')->add();
		}
		$table = getconfig("db_prefix") . "my_{$rs['tag']}";


		$sql = "
		DROP TABLE IF  EXISTS `{$table}` ;

		CREATE TABLE IF NOT EXISTS `{$table}` (
  `id` int(11) NOT NULL AUTO_INCREMENT,

  `category_id` int(10) NOT NULL COMMENT '文章分类ID',
   `name2` varchar(100) NOT NULL DEFAULT '' COMMENT '文章的网址,不带.html',
  `title` varchar(255) NOT NULL DEFAULT '' COMMENT '标题',
  `content` text COMMENT '文章内容',
  `keyword` varchar(255) DEFAULT NULL COMMENT '关键字',
  `desc` varchar(800) DEFAULT NULL COMMENT '网页描述',
  PRIMARY KEY (`id`),
  KEY `title` (`title`),
  KEY `category_id` (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='{$rs['name']}-{$rs['desc']}' AUTO_INCREMENT=1 ;
";
		$this->query($sql);
		return true;
	}

	/**
	$rs 为模型的记录 => 请确保数据正确,
	或模型的ID
	$old_rs => 原来的模型记录
	*/
	function updateTable($rs, $old_rs = null)
	{
		if(is_numeric($rs))
		{
			$rs = $this->pk($rs)->find();
		}
		$table = getconfig("db_prefix") . "my_{$rs['tag']}";

		$sql = array();
		$sql[] = "ALTER TABLE  `{$table}`  COMMENT = '{$rs['name']}-{$rs['desc']}'; ";

		if(isset($old_rs['tag']) && $old_rs['tag'] != $rs['tag'])
		{
			$old_table =  getconfig("db_prefix") . "my_{$old_rs['tag']}";
			$sql[] = "RENAME TABLE `{$old_table}` TO  `{$table}` ; ";
		}
		foreach($sql as $v)
		{
			$this->query($v);
		}	
		
	}
	/**
	$rs 为字段的记录
	*/
	function addField($rs)
	{
		$table = getconfig("db_prefix") . "my_{$rs['tag']}";

		$sql = "ALTER TABLE  `{$table}` ADD  `{$rs['field']}` VARCHAR( 512 ) NOT NULL COMMENT  '{$rs['name']}'";
		$this->query($sql);

	}
	/**
	$rs 为模型的记录 => 请确保数据正确,
	或模型的ID
	$old_rs => 原来的模型记录,必须参数
	*/
	function updateField($rs, $old_rs)
	{
		if(is_numeric($rs))
		{
			$rs = $this->table("mode_field")
			->as('a')
			->leftJoin("mode as b", "a.mid=b.id")
			->field("a.*,b.tag")
			->where("a.id='{$rs}'")->find();			
		}
		if(is_numeric($old_rs))
		{
			$old_rs = $this->table("mode_field")
			->as('a')
			->leftJoin("mode as b", "a.mid=b.id")
			->field("a.*,b.tag")
			->where("a.id='{$old_rs}'")->find();			
		}
		$rs = array_merge($old_rs, $rs);

		$table = getconfig("db_prefix") . "my_{$old_rs['tag']}";

		$sql = array();
		$sql[] = "ALTER TABLE  `{$table}` CHANGE  `{$old_rs['field']}`  `{$rs['field']}` VARCHAR( 512 ) CHARACTER SET utf8 COLLATE utf8_general_ci  NULL COMMENT  '{$rs['name']}' ";
		foreach($sql as $v)
		{
			$this->query($v);
		}	
		unset($rs['tag']);
		$this->values($rs)
			->table("mode_field")
			->update();		
	}
	function table2()
	{
		return $this->table("mode_field");
	}
	/***
	获取模型记录
	$key = 用什么做返回的键值, id or tag
	*/
	function getMode($key = 'id')
	{
		$rs = $this->order("porder")->findAll();
		$rec = array();
		foreach($rs as $k => $v)
		{
			$rec[$v[$key]] = $v;
		}
		return $rec;
	}
	/**#获取此模型下的字段#渲染
	$form_decode 是否对 form 进行解析
	$value_list = form 的VALUE值 
	*/
	function getModeFields($mid, $form_decode = true, $value_list = array())
	{
		$rs = $this->table2()->where("mid='{$mid}'")
			->order("porder,id")
			->findAll();

		

		if($form_decode)
		{
			foreach($rs as $k => $v)
			{			
				$v['value'] = isset($value_list[$v['field']]) ? $value_list[$v['field']] : '';
				$v = $this->formDecode($v);
				$rs[$k] = $v;
			}
		}
		return $rs;


	}
	/** 渲染 form 表单*/
	function formDecode($rt)
	{
		$form = html_entity_decode($rt['form']);

		
		
		
		//$form = "{editor}";


		$form_list = array(
		'{textarea}' => '<textarea name="{field}" placeholder="请输入{name}" class="layui-textarea">{value}</textarea>',	
		'{input}' => '<input type="text" value="{value}" name="{field}" placeholder="请输入{name}" class="layui-input">',	
		'{input2}' => '<input type="text" value="{value}" name="{field}" placeholder="请输入{name}" {required} class="layui-input">',	
		'{pic}' => '
			<div style="width:500px">
			<div class="layui-inline">
				<input type="text" id="{field}" name="{field}" value="{value}"  class="layui-input"/> 
			</div>
			<div class="layui-inline">
				<input type="button" id="btn_{field}" value="选择图片"  class="layui-input"/></div>
			<div class="layui-inline">
				<input type="button" id="btn2_{field}" value="将图片插入到内容页"  class="layui-input"/>
			</div>
			</div>
		

		'. "
<script>
KindEditor.ready(function(K) {
				var editor = K.editor({
					allowFileManager : true
				});

				K('#btn_{field}').click(function() {
					editor.loadPlugin('image', function() {
						editor.plugin.imageDialog({
							imageUrl : K('#{field}').val(),
							clickFn : function(url, title, width, height, border, align) {
								K('#{field}').val(url);
								editor.hideDialog();
							}
						});
					});
				});
				K('#btn2_{field}').click(function() {
					if(!K('#{field}').val()){
						alert('没有图片');return false;
					}
					K.insertHtml('textarea[name=\"content\"]', '<img src=\"'+ K('#{field}').val() + '\">')
				});
			
			
			});
</script>" ,	
		//'{editor}' => '{editor}',
		);
		if(!isset($form_list[$form]))
		{
			$str = substr($form,8);
			$par = parse_ini_string(str_replace(' ', "\n", $str));

			if(substr($form,0,8) == '{editor}')
			{
				$editor = load::loadClass('editor');
				!isset($par['name']) && $par['name'] = '{field}';
				!isset($par['value']) && $par['value'] = '{value}';
				!isset($par['toolbarset']) && $par['toolbarset'] = 'default';
				!isset($par['height']) && $par['toolbarset'] == 'txt' && $par['height'] = '150px';
				!isset($par['height']) && $par['toolbarset'] == 'simple' && $par['height'] = '200px';
				/*array(
										'name' => '{field}',	
										'value' => '{value}',
										'toolbarset' => 'default'
										)*/
				$form = $editor->kingedit4($par);
			}
			foreach($form_list as $k => $v)
			{
				$form = str_replace($k, $v, $form);
			}
		}
		else
		{
			$form = $form_list[$form];
		}		
		$form = str_replace('{value}', $rt['value'], $form);
		//$form = str_replace('#name', $rt['field'], $form);
		$form = str_replace('class=""', 'class="layui-input"', $form);
		

		foreach($rt as $k => $v)
		{
			$form = str_replace("{{$k}}", $v, $form);
		}
		$form = str_replace("{required}", ' required  lay-verify="required"', $form);

		$rt['form'] = $form;
		return $rt;
	}

	
}